// Copyright (c) 2022 Presto Labs Pte. Ltd.
// Author: hyuan

#include "coin2/exchange/coincheck/api_util/rate_tracker.h"

#include <algorithm>
#include <sstream>
#include <string>

#include <boost/algorithm/string/replace.hpp>
#include <glog/logging.h>

#include "coin2/base/proto_util.h"
#include "coin2/exchange/base/order/rate_config.h"

namespace coin2::exchange::coincheck::api_util {

constexpr auto EXAMPLE_SPOT_COINCHECK = R"(
"connection_config": {
  "key_filepath": "/home/ec2-user/config/trade/xunke18/coincheck/trade_key.json",
  "rate_limit_info": {
    "spot_coincheck": {
      "place_order": {
        "secs": 1,
        "reqs": 5
      }
    }
  }
},)";

template <class RateTracker>
void CheckFail(RateTracker&& rate_tracker, bool check_result) {
  if (!check_result) {
    LOG(INFO) << "Hit rate limit on [" << rate_tracker->GetName() << "]";
  }
}

CoincheckRateTracker::CoincheckRateTracker(
    const MarketExchangeApi& mea,
    const coin2::exchange::order::OrderConnectionConfig& cfg) {
  using RateConfig = coin2::exchange::base::order::RateConfig;
  if (mea.market == coin::proto::MarketType::Spot) {
    RateLimitInfoSpotCoincheck rate_config;
    RateConfig::Get()->GetConfig(mea, cfg, &rate_config);
    InitRateTracker(&rate_config, mea.String(), EXAMPLE_SPOT_COINCHECK);
  } else {
    CHECK(false) << "unsupported mea: " << mea.String();
  }
}

void CoincheckRateTracker::InitRateTracker(
    RateLimitInfoSpotCoincheck* rate_config,
    std::string_view mea_str,
    std::string_view example) {
  if (!rate_config || !rate_config->has_place_order()) {
    coin2::exchange::base::order::RateConfig::CheckFail(mea_str, example);
  }
  const auto& req_place_order = rate_config->place_order();
  LOG(INFO) << "\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
            << "\nOG request rate was set as below:\n"
            << "\nplace_order: [" << req_place_order.reqs() << "(reqs)/" << req_place_order.secs()
            << "(secs)]"
            << "\n\nOr you can configure customized rate in driver config. For example: " << example
            << "\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~";

  rate_tracker_placeorder_ =
      std::make_unique<FixedWindowRateTracker>(req_place_order.secs() * 1'000'000'000LL);
  rate_tracker_placeorder_->SetRateLimitInfo(req_place_order.reqs(), req_place_order.reqs());
  rate_tracker_placeorder_->SetName("coincheck_rate_tracker_place_order(1 sec)");

  rate_limit_report_writer_ = std::make_unique<RateLimitReportWriter>();
  rate_limit_report_writer_->SetRateLimitInfoString(rate_config);
}

bool CoincheckRateTracker::HasEnoughRateLimit(int64_t timestamp, ActionType action_type) {
  if (CheckEnableTime(timestamp, action_type) && CheckRateLimit(timestamp, action_type)) {
    return true;
  }

  rate_limit_report_writer_->SetHitRateLimit(timestamp, action_type);
  return false;
}

void CoincheckRateTracker::Push(int32_t num_reqs, int64_t timestamp, ActionType action_type) {
  if (action_type == ActionType::PLACE) {
    if (rate_tracker_placeorder_) {
      rate_tracker_placeorder_->Push(num_reqs, timestamp);
    }
  }
}

void CoincheckRateTracker::SetRateLimitInfoString(const google::protobuf::Message* message) {
  if (!rate_limit_report_writer_) {
    return;
  }
  rate_limit_report_writer_->SetRateLimitInfoString(message);
}

void CoincheckRateTracker::WriteRateLimitReportMessage(OrderLoggerCB callback) {
  if (!callback) {
    return;
  }
  rate_limit_report_writer_->Write(callback);
}

double CoincheckRateTracker::GetMaxRateUsedRatio(int64_t timestamp, ActionType action_type) {
  switch (action_type) {
    case ActionType::PLACE: {
      return GetMaxRateUsedRatio(rate_tracker_placeorder_, timestamp);
    }
    default: {
      // shouldn't reached here
      LOG(ERROR) << "ops~ something is wrong, action_type=" << action_type;
      return 0.;
    }
  }
}

bool CoincheckRateTracker::CheckEnableTime(int64_t timestamp, ActionType action_type) {
  if (timestamp >= enable_time_) {
    return true;
  }

  LOG_EVERY_N(WARNING, 50) << "Hit api temporary disabled until " << enable_time_ << ", "
                           << action_type;
  return false;
}

bool CoincheckRateTracker::CheckRateLimit(int64_t timestamp, ActionType action_type) {
  bool ret = true;
  if (action_type == ActionType::PLACE) {
    if (rate_tracker_placeorder_) {
      ret = rate_tracker_placeorder_->GetRemaining(timestamp) > 1;
      CheckFail(rate_tracker_placeorder_, ret);
    }
  }

  return ret;
}
}  // namespace coin2::exchange::coincheck::api_util
